package com.qxp.simplerpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qxp.simplerpc.api.Invoker;
import com.qxp.simplerpc.entity.InvokerMessage;
import com.qxp.simplerpc.entity.MonitorMessage;
import com.qxp.simplerpc.utils.HttpUtils;
import com.qxp.simplerpc.utils.ProtocolUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;


public abstract class AbstractInvoker implements Invoker {

    protected ApplicationContext applicationContext;


    public static Logger logger = LoggerFactory.getLogger(AbstractInvoker.class);

    @Override
    public void connect(InvokerMessage invokerMessage, long executeSeconds, boolean isSuccess, Throwable e) {
        invokerMessage.setSuccess(isSuccess);
        invokerMessage.setE(e);
        MonitorMessage monitorMessage = new MonitorMessage();
        BeanUtils.copyProperties(invokerMessage,monitorMessage);
        String monitor = applicationContext.getEnvironment().getProperty("spring.simplerpc.monitor.address");
        if(!StringUtils.isEmpty(monitor)){
            try {
                HttpUtils.httpPost(ProtocolUtils.withHttp(monitor), (JSONObject)JSONObject.toJSON(monitorMessage));
            } catch (Exception ex) {
                logger.error("connect to service error...",ex);
            }
        }
    }


}
